<template>
  <!--  <page-header-wrapper>-->
  <a-card :bordered='false' ref='card'>
    <div class='table-page-search-wrapper'>
      <a-form layout='inline'>
        <a-row :gutter='48'>
          <a-col :md='4' :sm='24'>
            <a-form-item label='项目名称'>
              <a-input v-model='queryParam.projectName' placeholder='输入项目名称' />
            </a-form-item>
          </a-col>
          <a-col :md='4' :sm='24'>
            <a-form-item label='申请年度'>
              <a-date-picker placeholder='选择年份' format='YYYY' picker='year' v-model='queryParam.reportYear' />
              <!-- <a-select v-model="queryParam.reportYear" placeholder="请选择" default-value="0">
                <a-select-option value="0">科技项目</a-select-option>
                <a-select-option value="1">英才计划</a-select-option>
                <a-select-option value="2">三新三化项目</a-select-option>
                <a-select-option value="3">标准化项目</a-select-option>
              </a-select> -->
            </a-form-item>
          </a-col>
          <a-col :md='6' :sm='24'>
            <a-form-item label='项目来源'>
              <a-select v-model='queryParam.projectSource' placeholder='请选择' default-value='0'>
                <a-select-option value='0'>国家省部级</a-select-option>
                <a-select-option value='1'>集团公司级</a-select-option>
                <a-select-option value='2'>海油发展重大专项</a-select-option>
                <a-select-option value='3'>海油发展重点攻关</a-select-option>
                <a-select-option value='4'>海油发展常规</a-select-option>
                <a-select-option value='5'>采油公司级</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='4' :sm='24'>
            <a-form-item label='项目经理'>
              <a-input v-model='queryParam.manager' placeholder='输入项目经理名' />
            </a-form-item>
          </a-col>
          <a-col :md='6' :sm='24'>
            <a-form-item label='承担单位' v-if='treeData'>
              <a-tree-select
                v-model='queryParam.unit'
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data='treeData'
              >
                  <span slot='title' slot-scope='{ value }' style='color: #08c'>
                    {{ value }}
                  </span>
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :md='4' :sm='24'>
            <a-form-item label='项目状态'>
              <a-select v-model='queryParam.status' placeholder='请选择' default-value='0'>
                <a-select-option value='0'>筹备中</a-select-option>
                <a-select-option value='1'>立项中</a-select-option>
                <a-select-option value='2'>实施中</a-select-option>
                <a-select-option value='3'>已完结</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='4' :sm='24'>
            <a-form-item label='项目专业'>
              <a-select v-model='queryParam.major' placeholder='请选择' default-value='0'>
                <a-select-option value='0'>FPSO</a-select-option>
                <a-select-option value='1'>边际油田</a-select-option>
                <a-select-option value='2'>系泊</a-select-option>
                <a-select-option value='3'>LNG</a-select-option>
                <a-select-option value='4'>非常规</a-select-option>
                <a-select-option value='5'>数字化</a-select-option>
                <a-select-option value='6'>其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='16' :sm='24'></a-col>
          <a-col :md='4' :sm='24' style='text-align: right'>
            <a-button @click='() => (this.queryParam = {})'>重置</a-button>
            <a-button style='margin-left: 8px' type='primary' @click='$refs.table.refresh(true)'>搜索</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- <div class="table-operator">
    </div> -->

    <div class='table-header'>
      <div style='display: flex;align-items: center;'>
        <div class='border'></div>
        <span class='table-header__title'>项目立项</span>
      </div>
      <div class='table-header__btn-group'>
        <a-popover title='表头设置' v-model='formTitleVisible' placement='bottom' trigger='click'>
          <template slot='content'>
            <div>
              <div
                v-for='(item, index) in columns'
                :key="index + '114514'"
                style='display: flex; justify-content: space-between; margin: 10px 0'
              >
                {{ item.title }}
                <a-switch :checked='item.showHeader' @change='onHeaderChange(item, index)' />
              </div>
            </div>
          </template>
          <a-button>表头设置</a-button>
        </a-popover>
        <a-button>批量导出</a-button>
        <a-button type='danger' ghost @click='deleteById'>批量删除</a-button>
        <a-button type='primary' icon='plus' @click='add()'>新增</a-button>
      </div>
    </div>
    <s-table
      ref='table'
      size='default'
      rowKey='id'
      :columns='columns'
      :data='loadData'
      :rowSelection='rowSelection'
      showPagination='auto'
      :scroll="{ x: 'max-content' }"
    >
        <span slot='serial' slot-scope='text, record, index'>
          {{ index + 1 }}
        </span>
      <span slot='status' slot-scope='text'>
          <span v-if='text === 0'> 筹备中 </span>
          <span v-else-if='text === 1' style='color: blue'> 立项中 </span>
          <span v-else-if='text === 2' style='color: green'> 实施中 </span>
          <span v-else-if='text === 3' style='color: red'> 已完结 </span>
        </span>
      <span slot='description' slot-scope='text'>
          <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
        </span>
      <span slot='projectSource' slot-scope='text, record, index'>
          {{ getSourceName(record.projectSource) }}
        </span>
      <span slot='major' slot-scope='text, record, index'>
          {{ getSubjectName(record.major) }}
        </span>
      <span slot='cycle' slot-scope='text, record, index'>
          {{ record.cycleStart }}~{{ record.cycleEnd }}
      </span>
      <span slot='unit' slot-scope='text, record, index'>
        {{ getUnitName(record.unitList, record.unit) }}
      </span>
      <span slot='action' slot-scope='text, record'>
          <template>
            <a @click='jumpToPage(record)'>{{ handleEdit(record) }}</a>
          </template>
        </span>
    </s-table>

    <create-form
      ref='createModal'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @cancel='handleCancel'
      @ok='handleOk'
    />
    <step-by-step-modal ref='modal' @ok='handleOk' />
  </a-card>
  <!--  </page-header-wrapper>-->
</template>
<script>
import moment from 'moment'
import { Ellipsis, STable } from '@/components'
import { deleteById, getPage } from '@/api/projectInitApply'

import StepByStepModal from '@/views/list/modules/StepByStepModal'
import CreateForm from '@/views/list/modules/CreateForm'

const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}
const sourceMap = {
  '0': '国家省部级',
  '1': '集团公司级',
  '2': '海油发展重大专项',
  '3': '海油发展重点攻关',
  '4': '海油发展常规',
  '5': '采油公司级'
}
const subjectMap = {
  '0': 'FPSO',
  '1': '边际油田',
  '2': '系泊',
  '3': 'LNG',
  '4': '非常规',
  '5': '数字化',
  '6': '其他'
}
export default {
  name: 'ProjectInitiationApply',

  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal
  },

  data() {
    return {
      // create model
      visible: false,
      //
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        if (requestParameters.unit && requestParameters.unit === '-1') {
          requestParameters.unit = null
        }
        if (requestParameters.reportYear) {
          let dateString = requestParameters.reportYear
          let dateObject = new Date(dateString)
          requestParameters.reportYear = dateObject.getFullYear()
        }
        console.log('latest request params is: ', JSON.stringify(requestParameters))
        return getPage(requestParameters)
          .then((res) => {
            console.log('resp is:', res)
            if (res.list) {
              if (res.list[0]) {
                console.log(res.list[0])
              }
            }
            let total = res.total
            let totalPage = Math.ceil(total / parameter.pageSize)
            return {
              pageSize: parameter.pageSize,
              pageNo: parameter.pageNo,
              totalCount: total,
              totalPage: totalPage,
              data: res.list
            }
          })
          .catch((err) => {
            console.log(err)
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      editName: null,
      formTitleVisible: false,
      titleVisible: true,
      dynamicWidth: 0,
      columnWidth: 0,
      treeData: null,
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' },
          key: 'id',
          dataIndex: 'id',
          showHeader: true
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          sorter: true,
          showHeader: true,
          key: 'projectName'
        },
        {
          title: '项目来源',
          dataIndex: 'projectSource',
          showHeader: true,
          key: 'projectSource',
          scopedSlots: { customRender: 'projectSource' },
          sorter: true
        },

        {
          title: '项目专业',
          dataIndex: 'major',
          showHeader: true,
          scopedSlots: { customRender: 'major' },
          key: 'major',
          sorter: true
        },
        {
          title: '承担单位',
          dataIndex: 'unit',
          showHeader: true,
          scopedSlots: { customRender: 'unit' },
          key: 'unit',
          // colSpan:0,
          sorter: true
        },
        {
          title: '项目周期',
          dataIndex: 'cycle',
          showHeader: true,
          scopedSlots: { customRender: 'cycle' },
          key: 'cycle',
          sorter: true
        },
        {
          title: '总预算',
          dataIndex: 'budget',
          showHeader: true,
          key: 'budget',
          sorter: true
        },
        {
          title: '立项状态',
          dataIndex: 'status',
          showHeader: true,
          key: 'status',
          sorter: true,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '项目经理',
          dataIndex: 'manager',
          key: 'manager',
          showHeader: true,
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          showHeader: true,
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },

  computed: {
    rowSelection() {
      console.log(this.selectedRowKeys)
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },

  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    }
  },

  created() {
    // getRoleList({ t: new Date() })
  },
  mounted() {
    // this.dynamicWidth = this.$refs.card.$refs.cardContainerRef.offsetWidth
    // this.columnWidth = this.$refs.card.$refs.cardContainerRef.offsetWidth
    // console.log(this.$refs.card.$refs.cardContainerRef.offsetWidth)
    // getDept().then(res=>{
    //   console.log(res);
    //     this.treeData = this.geneTree([res])
    //     console.log(this.treeData);
    //     })
  },

  methods: {
    getUnitName(unitList, unit) {
      if (unitList && unitList.length > 0) {
        let namesArray = unitList.map(item => item.value)
        return namesArray.join(',')
      } else if (unit == '-1') {
        return '全部'
      } else return '-'
    },
    getSubjectName(name) {
      return subjectMap[name] || '-'
    },
    getSourceName(name) {
      return sourceMap[name]
    },
    jumpToPage(record) {
      console.log(record.id)
      this.$router.push({ path: '/initManage/detail', query: { id: record.id } })
    },
    geneTree(data, res) {
      return data.map((ele) => {
        if (ele.children && ele.children.length > 0) {
          return {
            title: ele.title,
            key: ele.id,
            value: ele.id,
            children: this.geneTree(ele.children)
          }
        } else {
          return {
            title: ele.title,
            key: ele.id,
            value: ele.id,
            children: []
          }
        }
      })
    },
    deleteById() {
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        let promiseArray = []
        this.selectedRowKeys.forEach((ele) => {
          promiseArray.push(deleteById({ id: ele }))
        })
        Promise.all(promiseArray)
          .then((res) => {
            console.log(res[0].code)
            if (res[0].code === 200) {
              //  this.pageList();
              this.$refs.table.refresh()
              this.selectedRowKeys = []
            }
            console.log('All data fetched:', res)
          })
          .catch((error) => {
            console.error('Error in one of the requests:', error)
          })
        console.log(promiseArray)
      }
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      if (record.status === 0) {
        return '查看详情'
      }
      if (record.status === null) {
        return '查看详情'
      }
      if (record.status === 1) {
        return '查看详情'
      }
      if (record.status === 3) {
        return '查看详情'
      }
      if (record.status === '审核失败') {
        return '重新发起'
      }
    },

    pageList() {
      let requestParameters = this.queryParam
      console.log('loadData request parameters:', requestParameters)
      if (requestParameters.unit && requestParameters.unit === '-1') {
        requestParameters.unit = null
      }
      if (requestParameters.reportYear) {
        let dateString = requestParameters.reportYear
        let dateObject = new Date(dateString)
        requestParameters.reportYear = dateObject.getFullYear()
      }
      this.loadData = getPage(requestParameters).then((res) => {
        console.log(res)
        let list = res.list
        let total = res.total
        let totalPage = Math.ceil(total / requestParameters.pageSize)

        let tableData = {
          pageSize: requestParameters.pageSize,
          pageNo: requestParameters.pageNo,
          totalCount: total,
          totalPage: totalPage,
          data: list
        }
        this.loadData = tableData
        this.$refs.table.refresh()
      })
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('修改成功')
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    add() {
      this.$router.push({ path: '/initManage/addManage', query: { mode: 'add' } })
    },
    onHeaderChange(item, index) {
      // console.log(this.$refs.table.columns)
      if (!item.showHeader === false) {
        this.columns[index].className = 'tableHiddle'
      } else {
        this.columns[index].className = 'tableShow'
      }
      this.columns[index].showHeader = !item.showHeader
    }
  }
}
</script>

<style scoped lang='less'>
::v-deep .tableHiddle {
  display: none;
}

.tableShow {
  display: revert;
}

.table-header {
  .border {
    width: 3px;
    //height: 70%;
    height: 1.5em;
    background: #1890FF;
    margin-right: 8px;
  }

  //border-left: solid 2px #1890ff;
  padding-left: 8px;
  margin-bottom: 16px;
  // margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  &__title {
    font-size: 18px;
    line-height: 1em;
  }

  &__btn-group {
    display: flex;

    button:not(:last-child) {
      margin-right: 6px;
    }
  }
}
</style>
